package com.cfets.annualAssessment.weixinService.http;

import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.http.RequestExecutor;
import me.chanjar.weixin.common.util.http.Utf8ResponseHandler;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: pual
 * Date: 2015/12/11
 * Desc:
 */
public class MediaUploadRequestExecutor implements RequestExecutor<String, MultipartFile> {
    @Override
    public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, MultipartFile file) throws WxErrorException, ClientProtocolException, IOException {
        HttpPost httpPost = new HttpPost(uri);
        if (httpProxy != null) {
            RequestConfig response = RequestConfig.custom().setProxy(httpProxy).build();
            httpPost.setConfig(response);
        }

        if (file != null) {
            String BOUNDARY = "----------" + System.currentTimeMillis();
            StringBuilder sb = new StringBuilder();
            sb.append("--"); // 必须多两道线
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"media\";filename=\""
                    + file.getOriginalFilename() + "\"\r\n");
//                    + map.get("fileName") + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            byte[] head = sb.toString().getBytes("utf-8");
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
//            byte[] fileByte = (byte[]) map.get("byte");
            byte[] fileByte = file.getBytes();
            byte[] bufferOut = new byte[head.length+foot.length+fileByte.length];
            System.arraycopy(head,0,bufferOut,0,head.length);
            System.arraycopy(fileByte,0,bufferOut,head.length,fileByte.length);
            System.arraycopy(foot,0,bufferOut,head.length+fileByte.length,foot.length);

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

            multipartEntityBuilder
                    .addBinaryBody("media", bufferOut)
                    .setMode(HttpMultipartMode.RFC6532);
            multipartEntityBuilder.setBoundary(BOUNDARY);

            httpPost.setEntity(multipartEntityBuilder.build());
            httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
        }

        try{
            CloseableHttpResponse response = httpclient.execute(httpPost);
            String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
            WxError error = WxError.fromJson(responseContent);
            if (error.getErrorCode() != 0) {
                throw new WxErrorException(error);
            } else {
                return responseContent;
            }
        }finally {
            httpPost.releaseConnection();
        }
    }
}
